<template>
  <div>
    <el-container>
      <el-header>
        <el-button type="primary" @click="addTradeMark">+添加</el-button>
      </el-header>
      <el-main>
        <!--        品牌表格-->
        <el-table
          v-loading="loading"
          border
          :data="brandArr"
          highlight-current-row
          style="width: 100%"
        >
          <!--          序号-->
          <el-table-column
            label="序号"
            type="index"
            width="60"
            align="center"
          >
          </el-table-column>
          <!--          品牌名称-->
          <el-table-column
            label="品牌名称"
            prop="tmName"
            width="320">
          </el-table-column>
          <!--          品牌logo-->
          <el-table-column
            label="品牌LOGO"
            width="320"
          >
            <template slot-scope="scope">
              <el-image
                :src="scope.row.logoUrl"
                style="width: 65px;height: 65px">
                <div slot="error" class="image-slot">
                  <i style="font-family: 'iconfont';opacity: .6;
                  font-size: 36px;line-height: 70px;margin-left: 25px;">&#xe60e</i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <!--          操作-->
            <el-table-column
              label="操作"
              width="320">
              <template slot-scope="scope">
                <!--              修改品牌-->
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  type="warning"
                  @click="updateTradeMark(scope.row)">修改</el-button>
                <!--              删除品牌-->
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="danger"
                  @click="delTradeMark(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="brandFooter">
        <!--          分页器-->
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="brandInfo.total"
          hide-on-single-page
          layout="prev, pager, next, jumper,->,sizes,total"
          @size-change="handleChangeSize"
          @current-change="handleChangeCurrentPage"
        >
        </el-pagination>
      </el-footer>
    </el-container>
    <!--    添加品牌的弹出框-->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="tradeMarkInfo.id ?'修改品牌': '添加品牌'"
      @close="dialogClose"

      width="50%">
      <el-form ref="tradeMarkInfo" :model="tradeMarkInfo" label-width="80px" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tradeMarkInfo.tmName" style="width: 70%"></el-input>
        </el-form-item>
        <el-form-item label="品牌图片" prop="logoUrl" >
          <el-upload
            class="avatar-uploader"
            action="dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="tradeMarkInfo.logoUrl" :src="tradeMarkInfo.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="font-size: 12px">只能上传jpg/png文件，且不超过500kb</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="dialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="actionAddOrUpdateBrand">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: "TradeMark",
  data() {
    return {
      loading: false, // 控制loading效果
      // 当前页面
      currentPage: 1,
      pageSize: 5,
      dialogVisible: false,
      // 表单校验规则
      rules:{
        // 品牌名称验证规则
        tmName:[{required: true, message: '请输入品牌名称', trigger: 'blur'},
          {min: 2,max: 10,message: '品牌名称长度应该为2到10位',trigger: 'blur'}],
        // 品牌logo验证规则
        logoUrl:[{ required: true, message: '请上传品牌logo'}]
      },
      // 添加或添加品牌的表单数据
      tradeMarkInfo: {
        id: undefined,
        tmName: '',
        logoUrl: ''
      },
    }
  },
  computed: {
    // 品牌表格的数据
    brandArr() {
      return this.$store.getters.records
    },
    // 数据总条数
    ...mapState('tradeMark', ['brandInfo'])
  },
  methods: {
    // 派发actions获取品牌分类的基本信息
    actionsGetBrandList() {
      this.loading = true
      this.$store.dispatch('tradeMark/getBrandList', {page: this.currentPage, limit: this.pageSize}).then(res=>{
        this.loading = false
      }).catch(err=>{
        this.loading = false
      })
    },
    // 当前每页的个数被改变
    handleChangeSize(currentPageSize) {
      this.pageSize = currentPageSize
      this.actionsGetBrandList()
    },
    // 改变当前页
    handleChangeCurrentPage(currentPage) {
      this.currentPage = currentPage
      this.actionsGetBrandList()
    },
    // 打开添加品牌的dialog
    addTradeMark() {
      this.tradeMarkInfo.tmName = ''
      this.dialogVisible = true
    },
    // 打开修改品牌的dialog
    updateTradeMark(tradeInfo) {
      // 重置表单信息为修改的信息
      this.tradeMarkInfo.id = tradeInfo.id
      this.tradeMarkInfo.tmName = tradeInfo.tmName
      this.tradeMarkInfo.logoUrl = tradeInfo.logoUrl
      this.dialogVisible = true
    },
    // 图片上传之前的回调
    beforeAvatarUpload(file){
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 0.5;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 500kb!');
      }
      return isJPG && isLt2M;
    },
    // 图片上传成功的回调
    handleAvatarSuccess(res) {
      if(res.code !== 200) {
        this.$message.error('上传失败')
      }else {
        this.tradeMarkInfo.logoUrl = res.data
      }
    },
    // 编辑或者添加品牌
    actionAddOrUpdateBrand() {
      // 表单校验
      this.$refs.tradeMarkInfo.validate(async valid=>{
        if(valid) {
          let res = await this.$API.tradeMark.apiAddOrUpdateBrand(this.tradeMarkInfo)
          if(res.code === 200) {
            this.$message.success('添加或修改成功')
            this.dialogVisible =false
            this.actionsGetBrandList()
          }else {
            this.$message.error('添加或修改失败')
            this.dialogVisible = false
          }
        }else {
          this.$message.error('请填写表单的信息')
        }
      })
    },
    // 删除品牌信息
    delTradeMark(tradeInfo){
        this.$confirm(`是否删除品牌${tradeInfo.tmName}?`,'警告',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(async ()=>{
          let res = await this.$API.tradeMark.apiDeleteBrand(tradeInfo.id)
          if (res.code === 200) {
            // 如果当前页就一条数据，当删除后要跳转到前一页
            this.currentPage = this.brandArr.length < 2 ? this.currentPage -1 : this.currentPage
            this.actionsGetBrandList()
            this.$message.success('删除成功')
          }else {
            this.$message.error('删除失败')
          }
        }).catch(e=>{
          this.$message.warning('已取消')
        })
    },
    // dialog框关闭前的回调【重置表单】
    dialogClose() {
      // 重置表单
      this.$refs.tradeMarkInfo.resetFields()
    }
  },
  mounted() {
    // 派发actions获取品牌分类基本信息
    this.actionsGetBrandList()
  }
}
</script>

<style scoped>
.brandFooter {
  text-align: center;
}
.avatar-uploader{
  width: 30%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
